﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PeiYue.Common.Helper;
using PeiYue.Common.HttpContextUser;
using PeiYue.IServices.Purchase;
using PeiYue.IServices.Store;
using PeiYue.Model;
using PeiYue.Model.Dto.Store;
using PeiYue.Model.ERPModels;
using PeiYue.Model.Models.Store;
using SQLitePCL;

namespace PeiYue.Api.Controllers.Store
{
    /// <summary>
    /// 投递
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class DeliveryController : ControllerBase
    {
        readonly ISaleDeliveryHeaderServices _saleDeliveryHeaderServices;
        readonly ISaleDeliveryDetailServices _saleDeliveryDetailServices;
        readonly IDeliveryServices _deliveryServices;
        readonly IDeliveryLogServices _deliveryLogServices;
        readonly IStoreSortingLogServices _storeSortingLogServices;
        readonly IReceiptRecordServices _receiptRecordServices;
        readonly IPurchaseOrderDetail _purchaseOrderDetail;
        readonly IUser _user;
        readonly IMapper _mapper;
        public DeliveryController(ISaleDeliveryHeaderServices saleDeliveryHeaderServices,
         ISaleDeliveryDetailServices saleDeliveryDetailServices,
         IDeliveryServices deliveryServices,
          IDeliveryLogServices deliveryLogServices,
          IStoreSortingLogServices storeSortingLogServices,
          IReceiptRecordServices receiptRecordServices,
           IPurchaseOrderDetail purchaseOrderDetail,
         IUser user, IMapper mapper)
        {
            _saleDeliveryHeaderServices = saleDeliveryHeaderServices;
            _saleDeliveryDetailServices = saleDeliveryDetailServices;
            _deliveryServices = deliveryServices;
            _deliveryLogServices = deliveryLogServices;
            _storeSortingLogServices = storeSortingLogServices;
            _receiptRecordServices = receiptRecordServices;
            _purchaseOrderDetail = purchaseOrderDetail;
            _user = user;
            _mapper = mapper;
        }
        /// <summary>
        ///  扫码投递
        /// </summary>
        /// <param name="dto">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<DeliveryRecordDto>> ScanDelivery(ScanDeliveryDto dto)
        {
            var data = new MessageModel<DeliveryRecordDto>() { success = false };
            if (_user.ID == 0)
            {
                data.status = 401;
                data.msg = "很抱歉，您无权访问该接口，请确保已经登录!";
                return data;
            }
            string barCode = dto.OrderDetailId;
            if (string.IsNullOrWhiteSpace(barCode) || barCode.Length < 9)
            {
                data.success = false;
                data.status = 500;
                data.msg = "无效标签";
                //记录错误条码
                Common.LogHelper.SerilogServer.WriteLog("ScanDelivery", new string[] { barCode });
                return data;
            }
            var sortingLogDto = await _deliveryServices.GetSortingLogDto(barCode, DateTime.Now.Date);
            if (sortingLogDto == null)
            {
                //记录错误条码
                Common.LogHelper.SerilogServer.WriteLog("ScanDelivery", new string[] { barCode });
                data.success = false;
                data.status = 500;
                data.msg = "无效标签";
                return data;
            }
            //var recordModel = await _deliveryServices.QueryModel(t => t.BarCode == barCode && t.UpdateUser != _user.ID && t.Status == 0);
            //if (recordModel!=null && !dto.IsCover)
            //{
            //    data.success = true;
            //    data.msg = "已经投递";
            //    data.response = true;
            //    return data;
            //}
            string priority = string.Empty;
            int orderDetailId = sortingLogDto.SaleId;
            var dao = await _deliveryServices.QueryModel(t => t.BarCode == barCode && t.Status == 0);
            if (dao != null)
            {
                data.success = false;
                data.status = 209;
                data.msg = "已投递";
                return data;
            }
            if (dao == null)
                dao = new DeliveryRecordDao();
            dao.OrderDetailId = orderDetailId;
            dao.Type = 0;
            dao.BarCode = barCode;
            dao.SkuQty = sortingLogDto.Qty;
            dao.SkuPrice = sortingLogDto.Price;
            SaleDeliveryHeader headerDao = null;
            var skuModel = await _saleDeliveryDetailServices.QueryModel(t => t.销售ID == dao.OrderDetailId);
            if (skuModel != null)
            {
                dao.OrderId = skuModel.单号;
                dao.SkuCode = skuModel.存货编码;
                dao.SkuName = skuModel.品名;
                dao.SkuSpec = skuModel.单位;
                dao.LineNumber = skuModel.行号.HasValue ? skuModel.行号.Value : 0;
                dao.SortingMode = skuModel.分拣方式;
                dao.PackQty = 1;// model.包裹数.HasValue?model.包裹数.Value:1;
                headerDao = await _saleDeliveryHeaderServices.QueryModel(t => t.单号 == skuModel.单号, t => new SaleDeliveryHeader() { 客户 = t.客户, 客户编号 = t.客户编号, 优先级 = t.优先级 });
                if (headerDao != null)
                {
                    dao.CustomerCode = headerDao.客户编号;
                    dao.CustomerName = headerDao.客户;
                    priority = string.IsNullOrWhiteSpace(headerDao.优先级) ? "" : headerDao.优先级;
                    dao.Priority = priority;
                }
            }
            dao.CreateTime = DateTime.Now;
            dao.CreateUser = _user.ID;
            dao.UpdateTime = DateTime.Now;
            dao.UpdateUser = _user.ID;
            dao.Status = 0;
            bool flag = false;
            long id = 0;
            if (dao.Id > 0)
            {
                id = dao.Id;
                flag = await _deliveryServices.Update(dao);
            }
            else
            {
                id = await _deliveryServices.Add(dao);
                flag = id > 0;
            }
            if (flag)
            {
                var logDao = new DeliveryRecordLogDao();
                logDao.Status = 0;
                logDao.OrderDetailId = orderDetailId;
                logDao.CreateTime = DateTime.Now;
                logDao.CreateUser = _user.ID;
                logDao.BarCode = barCode;
                await _deliveryLogServices.Add(logDao);
                data.success = true;
                data.msg = "投递成功";
                data.response = new DeliveryRecordDto()
                {
                    Id = id,
                    OrderDetailId = dao.OrderDetailId,
                    BarCode = barCode,
                    CustomerCode = priority + (string.IsNullOrWhiteSpace(dao.CustomerCode) ? "" : dao.CustomerCode),
                    SkuName = dao.SkuName,
                    SkuSpec = dao.SkuSpec,
                    SkuQty = dao.SkuQty
                };
                if (barCode.ToUpper().Contains("G"))
                {
                    //投递没收货  自动收货
                    var receiptModel = await _receiptRecordServices.QueryModel(t => t.BarCode == barCode && t.Status == 1);
                    if (receiptModel == null)
                    {
                        var receiptRecordModel = new ReceiptRecord();
                        receiptRecordModel.BarCode = barCode;
                        receiptRecordModel.Type = 1;
                        receiptRecordModel.UpdateUser = _user.ID;
                        receiptRecordModel.ReceiptQty = dao.SkuQty;
                        receiptRecordModel.CustomerCode = string.IsNullOrWhiteSpace(dao.CustomerCode) ? "" : dao.CustomerCode;
                        receiptRecordModel.SkuCode = dao.SkuCode;
                        int saleId = Convert.ToInt32(barCode.Split(new char[] { 'G', 'J', 'K' }).FirstOrDefault());
                        var purchaseOrderDetailDto = await _purchaseOrderDetail.GetPurchaseDetailBySaleId(saleId);
                        if (purchaseOrderDetailDto != null)
                        {
                            receiptRecordModel.SupplierCode = purchaseOrderDetailDto.SupplierCode;
                            receiptRecordModel.FID = purchaseOrderDetailDto.fID;
                        }
                        await _receiptRecordServices.Add(receiptRecordModel);
                    }
                }
            }
            return data;
        }
        /// <summary>
        ///  获取已投递列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<DeliveryRecordDto>>> GetDeliveryRecordList()
        {
            var list = await _deliveryServices.GetDeliveryRecordList(_user.ID);
            return new MessageModel<List<DeliveryRecordDto>>()
            {
                msg = "获取成功",
                success = true,
                response = list
            };
        }
        /// <summary>
        /// 撤销投递
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Revoke(RevokeDto dto)
        {
            var data = new MessageModel<string>() { success = false };
            if (_user.ID == 0)
            {
                data.status = 401;
                data.msg = "很抱歉，您无权访问该接口，请确保已经登录!";
                return data;
            }
            var model = await _deliveryServices.QueryModel(t => t.Id == dto.Id);
            if (model == null)
            {
                data.success = false;
                data.status = 500;
                data.msg = "参数无效";
                return data;
            }
            model.Status = 1;
            if (await _deliveryServices.Update(model))
            {
                var logDao = await _deliveryLogServices.QueryModel(t => t.BarCode == model.BarCode && t.OrderDetailId == model.OrderDetailId && t.CreateUser == _user.ID && t.Status == 0);
                if (logDao != null)
                {
                    await _deliveryLogServices.UpdateLog(logDao);
                }
                data.success = true;
                data.msg = "撤销成功";
            }
            return data;
        }
        /// <summary>
        ///  获取待投递产品列表
        /// </summary>
        /// <param name="customerCode">客户编号</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<DeliveryRecordDto>>> GetDeliverySkuList(string customerCode)
        {
            var list = await _saleDeliveryHeaderServices.GetDeliverySkuList(customerCode);
            return new MessageModel<List<DeliveryRecordDto>>()
            {
                msg = "获取成功",
                success = true,
                response = list
            };
        }

        /// <summary>
        ///  获取投递客户编号
        /// </summary>
        /// <param name="query">查询</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<string>>> GetDeliveryCusNo()
        {
            DeliveryDto query = new DeliveryDto();
            List<string> cusCodes = new List<string>();
            var list = await _saleDeliveryHeaderServices.GetDeliveryList(query);
            cusCodes = list.OrderBy(i => i.CusId).Select(i => i.CustomerCode).Distinct().ToList();
            return new MessageModel<List<string>>()
            { msg = "获取成功", success = true, response = cusCodes };
        }

        /// <summary>
        ///  获取投递明细
        /// </summary>
        /// <param name="query">查询</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<DeliveryRecordDto>>> GetDeliveryDetail([FromQuery] DeliveryDto query)
        {
            MessageModel<List<DeliveryRecordDto>> dto = new MessageModel<List<DeliveryRecordDto>>() { };
            var list = await _saleDeliveryHeaderServices.GetDeliveryList(query);
            list.ForEach(i => i.Status = string.IsNullOrEmpty(i.DeliveryUser) ? 0 : 1);
            dto.response = list;
            return dto;
        }



    }
}
